import axios from "axios";
import {ElMessage} from "element-plus";

const service = axios.create({
	baseURL: "http://localhost:8888",
	timeout: 5000,
	withCredentials: true
})

service.interceptors.request.use(
	(config) => {
		
		if (localStorage.getItem("token")) {
			const token = localStorage.getItem("token")
			config.headers["Authorization"] = `Bearer ${token}`
		}
		return config
	},
	(error) => {
		console.log(error)
		return Promise.reject(error)
	}
)

service.interceptors.response.use(
	(response) => {
		if (response.status !== 200) {
			ElMessage({
				message: response.data || "Error",
				type: "error",
				duration: 5 * 1000
			})
			return Promise.reject(new Error(response.data || "Error"))
		} else {
			return response;
		}
	},
	(error) => {
		console.log("err" + error)
		return Promise.reject(error)
	}
)

export default service;